import request from "@/utils/request";
import type { SftpFile, SftpDTO, R, SseEvent, SseEventReceived } from "@/types";

// --- 新增 SftpFileContentDTO 类型定义 ---
export interface SftpFileContentDTO {
  content: string;
  lastModified: number; // Unix timestamp in milliseconds
}
// --- 新增 SaveFileContentParams 类型定义 ---
export interface SaveFileContentParams {
  id: string;
  path: string;
  content: string;
  lastModified: number; // Unix timestamp in milliseconds
}
// --- --- --- --- --- --- --- --- --- --- ---

function ls(id: string, path?: string): Promise<R<SftpDTO>> {
  return request.get("/api/sftp/ls", { params: { id: id, path: path } });
}

function download(id: string, path: string): void {
  // url编码path
  const _path = encodeURIComponent(path);
  window.open(`/api/sftp/download?id=${id}&path=${_path}`);
}

function rm(id: string, path: string): Promise<R<any>> {
  return request.post("/api/sftp/delete", {}, { params: { id: id, path: path } });
}

function uploadSSE(id: string, path: string, file: File, received: SseEventReceived) {
  const formData = new FormData();
  formData.append("file", file);
  formData.append("id", id);
  formData.append("path", path);

  fetch("/api/sftp/upload-sse", {
    method: "POST",
    body: formData
  }).then((response) => {
    if (response.body === null) {
      throw new Error("Response body is null");
    }
    let buffer = "";

    const reader = response.body.getReader();
    return new ReadableStream({
      start(controller) {
        function push() {
          reader.read().then(({ done, value }) => {
            if (done) {
              controller.close();
              return;
            }
            const text = new TextDecoder("utf-8").decode(value);

            buffer += text;

            let readLineIndexOf = buffer.indexOf("\n\n");

            while (readLineIndexOf != -1) {
              let firstObjStr = buffer.substring(0, readLineIndexOf);

              const lines = firstObjStr.split("\n");

              const event: SseEvent = {
                data: "",
                event: "",
                id: ""
              };

              lines.forEach((line: string) => {
                if (line.indexOf("id:") != -1) {
                  event.id = line.substring(3);
                } else if (line.indexOf("event:") != -1) {
                  event.event = line.substring(6);
                } else if (line.indexOf("data:") != -1) {
                  event.data = line.substring(5);
                }
              });
              received(event);

              buffer = buffer.substring(readLineIndexOf + 1);
              readLineIndexOf = buffer.indexOf("\n\n");
            }

            push();
          });
        }

        push();
      }
    });
  });
}

// --- 新增 API 函数 ---
/**
 * 获取 SFTP 文件内容和元数据
 * @param connectionId SFTP 连接 ID
 * @param path 文件路径
 */
function fetchFileContent(connectionId: string, path: string): Promise<R<SftpFileContentDTO>> {
  return request.get("/api/sftp/edit/content", { params: { id: connectionId, path: path } });
}

/**
 * 保存 SFTP 文件内容
 * @param params 保存参数，包含连接ID、路径、内容和最后修改时间
 */
function saveFileContent(params: SaveFileContentParams): Promise<R<void>> {
  return request.post("/api/sftp/edit/save", params);
}
// --- --- --- --- --- --- --

export default {
  ls,
  download,
  rm,
  uploadSSE,
  fetchFileContent, // 导出新函数
  saveFileContent   // 导出新函数
};
